<?php

class CSVDataParser extends DataParser {

    public function parseItem($item) {
        $event = new NewsItem();
        $event->setAuthor($item['author']);
        $event->setDescription($item['description']);
        $event->setContent($item['description']);
        $event->setPubDate(new DateTime($item['createDate']));
        $event->setId($item['id']);
        $event->setTitle($item['title']);
        $event->setLink('http://www.ntpc.gov.tw/ap/newcalendar/newcalendar_info.jsp?id=' . $item['id']);
        return $event;
    }

    public function parseData($data) {

        $str = str_replace("\"\n", "\"\r", $data);
        $arr = str_getcsv($str, "\r");
        $fields = str_getcsv($arr[0]);
        $array = array();
        foreach ($arr as $i => $msg) {
            if ($i != 0) {
                $arrs = str_getcsv($msg);
                foreach ($fields as $j => $field) {
                    $detail[$field] =  $arrs[$j];
                }
                $array[] = $this->parseItem($detail);
            }
        }
        $this->setTotalItems(count($array));
        return $array;
    }
}
